<?php

/**
 * Subclass for representing a row from the 'mail_task' table.
 *
 * 
 *
 * @package lib.model
 */ 
class MailTask extends BaseMailTask
{
    const PRIORITY_LOW         = 1;
    const PRIORITY_NORMAL      = 2;
    const PRIORITY_HIGH        = 3;
    const LIMIT_SENDING_MAILS_PER_TIME = 10;
    /**
     * 
     * returns array of priorities with translation
     */
    public static function getPriorityList()
    {
        return $priorities = array(self::PRIORITY_LOW => sfContext::getInstance()->getI18N()->__('low')
                          , self::PRIORITY_NORMAL => sfContext::getInstance()->getI18N()->__('normal')
                          , self::PRIORITY_HIGH => sfContext::getInstance()->getI18N()->__('high')
                  );
    }
    /**
     * 
     * create new mailtask and save it in db, returns true on success
     * @param int $userId
     * @param int $priority
     * @param string $subject
     * @param mail $mailto
     * @param string $title
     * @param string $body
     * @param  $sender
     * @param mail $mailfrom
     * @param timestamp $startAtTm
     * @throws Exception if mails invalid
     */
    public static function createNew($userId, $priority, $subject, $mailto, $title, $body, $sender, $mailfrom, $startAtTm = 0)
    {
        $mailTask = new MailTask();
        $mailTask->setUserId($userId);
        $mailTask->setStatusId(MyConstants::STATUS_NEW);
        $mailTask->setPriority($priority);
        //TODO: if recipient_id is set, get e-mail ($mailto) from user table
        $mailTask->setSubject($subject);
        $mailTask->setMailto($mailto);
        $mailTask->setTitle($title);
        $mailTask->setBody($body);
        $mailTask->setSender($sender);
        $mailTask->setMailfrom($mailfrom);
        //$mailTask->setStartAt($start_at == 0 ? time(): $start_at);
        if( !(self::validateTask($mailTask)) )
        {
        	throw new Exception('Mail task not valid!');
        }
        // setSentAt() must by set when mail will be sended, $start_at = time()
        $mailTask->save();
        return true;
    }
    /**
     * 
     * task validation 
     * @param obj $task
     */
    public static function validateTask($task)
    {
        /* @var $task MailTask */
        /* @var $validator sfEmailValidator */
        $validator = new sfEmailValidator();
        $emailfrom = $task->getMailfrom();
        $mailto = $task->getMailto();
        $validator->initialize(sfContext::getInstance()
                              , array('strict' => true
                                      , 'email_error' => 'This E-mail is invalid.'));
        if( !($res = $validator->execute($emailfrom, $email_error)) )
        {
            return false;
        }
        if( !($res1 = $validator->execute($mailto, $email_error)) )
        {
            return false;
        }
        return true;
    }

    public static function sendMailTasks()
    {
        $start = 'Corn_starts_send_mailtasks';
        SymConfig::set($start, time());
        $c = new Criteria();
        $c->add(MailTaskPeer::STATUS_ID, MyConstants::STATUS_NEW);
        $c->addDescendingOrderByColumn(MailTaskPeer::PRIORITY);
        $c->addDescendingOrderByColumn(MailTaskPeer::ID);
        $c->setLimit(MailTask::LIMIT_SENDING_MAILS_PER_TIME);
        $tasks = MailTaskPeer::doSelect($c);
        if(empty($tasks))
        {
            $start_empty = 'Corn_starts_send_mailtasks_empty';
            SymConfig::set($start_empty, time());
        }
        $count = 0;
        $arIds = array();
        foreach( $tasks as $key => $task )
        {
            $arIds[$task->getId()] = $task->getId();
            $count++;
            /* @var $task MailTask */
            if( !$task->getMailto() )
            {
                continue;
            }
            $senderMail = $task->getMailfrom();
            $senderName = $task->getSender();
            $recipient = $task->getMailto();
            $subject = $task->getSubject();
            $body = $task->getBody();
            
            $mail = new sfMail();
            $mail->initialize();
            $mail->addCustomHeader('MIME-Version', '1.0');
            $mail->addCustomHeader('Content-type', 'text/html;charset=utf-8');
    
            $mail->setCharset('utf-8');
    
            // definition of the required parameters
            $mail->setSender($senderMail, $senderName);
            $mail->setFrom($senderMail, $senderName);
    
            $mail->addAddress($recipient);
    
            $mail->setSubject($subject);
            $mail->setBody($body);
            
            $mail->send();
    
//            $task->setStatusId(MyConstants::STATUS_APPROVED);
//            $task->setSentAt(time());
//            
//            $task->save();
            $end = 'Cron_sends_mails_end';
            SymConfig::set($end, time());
    	}
    	$c = new Criteria();
        $c->add(MailTaskPeer::ID, $arIds, Criteria::IN);
 
        // set the update criteria
        $update = new Criteria();
        $update->add(MailTaskPeer::STATUS_ID, MyConstants::STATUS_APPROVED);
 
        // we need the connection for update, so get default connection
        $con = Propel::getConnection();
 
        // finally, do the update
        BasePeer::doUpdate($c, $update, $con);
        
        $countLast = 'coun_Cron_last_sended_mails';
        SymConfig::set($countLast, $count);

    }
}
